package main

import (
	"fmt"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"os"
	"strings"
)

var (
	Path    string
	ID      string
	Version string
	Var1    string
	Var2    string
)
var flags *pflag.FlagSet

func init() {
	resetFlags()
}

// Explicitly define a method to facilitate tests
func resetFlags() {
	flags = &pflag.FlagSet{}
	flags.StringVarP(&Path, "Path", "d", "", "程序路径")
	flags.StringVarP(&ID, "ID", "C", "", "通道ID")
	flags.StringVarP(&Version, "Version", "V", "", "程序版本号")
	flags.StringVar(&Var1, "Var1", "", "冗余1")
	flags.StringVar(&Var2, "Var2", "", "冗余2")

}

// 将flag标志 绑定到 command上
func attachFlags(cmd *cobra.Command, names []string) {
	cmdFlags := cmd.Flags()
	for _, name := range names {
		if flag := flags.Lookup(name); flag != nil {
			cmdFlags.AddFlag(flag)
		} else {
			fmt.Errorf("could not find flag '%s' to attach to command '%s'", name, cmd.Name())
		}
	}
}

var myUtilCmd = &cobra.Command{
	Use:   "myutil",
	Short: "myutil是我的工具集的意思，可以提供多种自定义快捷脚手架工具",
	Long:  "myutil是我的工具集的意思，可以提供多种自定义快捷脚手架工具",
}

// 模拟子命令，用到不同的标志
// / cmd1 仅适用到Path、ID
func listCmd() *cobra.Command {
	listCmd := &cobra.Command{
		Use:   "list",
		Short: "list files.",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("args", args)
			fmt.Println("list files...", Path)
			fmt.Println("ID : ", ID)
		},
	}
	flagList := []string{
		"Path",
		"ID",
	}
	attachFlags(listCmd, flagList)
	return listCmd
}

func main() {

	myUtilCmd.AddCommand(listCmd())
	myUtilCmd.AddCommand(versionCmd("1.0"))
	mainFlags := myUtilCmd.PersistentFlags()
	mainFlags.String("logging-level", "", "Legacy logging level flag")
	mainFlags.String("Var2", "default value", "Var2")
	viper.BindPFlag("logging_level", mainFlags.Lookup("logging-level"))
	mainFlags.MarkHidden("logging-level")
	if myUtilCmd.Execute() != nil {
		os.Exit(1)
	}
}

func versionCmd(defaultVersion string) *cobra.Command {
	aboutCmd := &cobra.Command{
		Use:   "version",
		Short: "显式设置版本和更新描述",
		Run: func(cmd *cobra.Command, args []string) {
			if Version == "" {
				Version = defaultVersion
			}
			//strings.Join(args, " ")用于将输入数组组装为一个string文本
			fmt.Printf("版本[%s]...补充说明：%s\n", Version, strings.Join(args, " "))

			for _, key := range []string{
				"Version",
				"ID",
				"Var1",
				"Var2",
				"logging-level",
			} {
				fmt.Printf("%s is: %s\n", key, cmd.Flags().Lookup(key).Value)
			}

		},
	}
	flagList := []string{
		"Version",
		"ID",
		"Var1",
		"Var2",
		//"logging-level",
	}
	attachFlags(aboutCmd, flagList)
	return aboutCmd
}
